/**
 *
 * Copyright 2016-present authing
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import React from 'react';
import { connect } from 'react-redux';
import CodePush from 'react-native-code-push';
import { bindActionCreators } from 'redux';
import store from 'react-native-simple-store';
import {
  Alert,
  Platform,
  AppState,
  Text, TouchableOpacity, StyleSheet,
  DeviceEventEmitter,
  InteractionManager
} from 'react-native';

import { createIconSetFromIcoMoon } from 'react-native-vector-icons';
import icoMoonConfig from '../config/icoMoonConfig.json';
const Icon = createIconSetFromIcoMoon(icoMoonConfig);
import Badge from '../components/Badge';
import AliyunPush from 'react-native-aliyun-push';

import Main from '../pages/MainPage/Main';
import * as authCreators from '../actions/auth';
import * as teamCreators from '../actions/team';
import * as userCreators from '../actions/user';
import * as msgCreators from '../actions/msg';
import * as noticeDeviceCreators from '../actions/noticeDevice';
import SCRMWebViewPage from '../pages/ItemDetail/SCRMWebViewPage';
import { HOME_ROUTE } from '../constants/VueRoutes';
import codePushConfig from '../config/CodePush';
import { getDeviceInfo } from '../utils/DeviceInfo';
import { getLinkSimple }  from '../utils/VueLinkUtil';


class MainContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      article: {
        "url": ''
      }
    }

    this.navigateToLink = this.navigateToLink.bind(this);
    this.go = this.go.bind(this);
    this.onMessage = this.onMessage.bind(this);
  }

  // static navigationOptions = {
  //   title: '工作台',
  //   tabBarIcon: ({ tintColor }) => (
  //     <Icon name="workbench_n" size={24} color={tintColor} />
  //   )
  // };

  static navigationOptions = ({ navigation }) => {
    const {state} = navigation;
    const {params} = state;
    let title = state.routeName === 'Main' ? '工作台' : '...';
    if (state.params && state.params.title) {
      title = `${state.params.title}`;
    }
    // const count = params && params.count ? params.count : '';
    // console.log('msgContainer', JSON.stringify(state.params))
    return {
      title: title,
      tabBarVisible: true,
      tabBarIcon: ({ tintColor }) => (
        <Badge show={false}>
          <Icon name="workbench_n" size={24} color={tintColor} />
        </Badge>
      ),
      headerRight:
      (
        <TouchableOpacity 
          style={styles.refreshStyle}
          onPress={() => {
            navigation.state.params.handleRefresh && navigation.state.params.handleRefresh();
        }}>
          <Text
          style={styles.refreshTextStyle}
          >刷新</Text>
        </TouchableOpacity>
      )
    };
  };

  componentWillReceiveProps(nextProps) { 
    // console.log('nextProps', nextProps, nextProps.user)
    if (!this.isInit && nextProps.user.user) {
      this.initNoticeDevice(nextProps.user.user)
      this.isInit = true
    }
  }

  forceUpdate () {
    const mode = __DEV__ ? 'debug' : 'release';
    const deploymentKey = codePushConfig[Platform.OS][mode]
    CodePush.sync({
      deploymentKey: deploymentKey, // scrm ios release
      updateDialog: {
        appendReleaseDescription: true,
        descriptionPrefix:"更新内容：",
        mandatoryContinueButtonLabel:"立即更新",
        mandatoryUpdateMessage: 'SCRM有新版本',
        optionalIgnoreButtonLabel: '稍后',
        optionalInstallButtonLabel: '后台更新',
        optionalUpdateMessage: 'SCRM有新版本了，是否更新？',
        mandatoryUpdateMessage: 'SCRM有新的更新!',
        title: '更新提示'
      },
      installMode: CodePush.InstallMode.IMMEDIATE
    });
  }

  initNoticeDevice (user) {
    const { noticeDiviceActions } = this.props;

    AliyunPush.getDeviceId()
    .then((deviceId)=>{
        console.log("AliyunPush deviceId:"+deviceId +' : ' +Platform.OS);

        const deviceInfo = getDeviceInfo()
        let noticeDevice  = {}

        noticeDevice['app_device_id']     = deviceInfo['unique_id']
        noticeDevice['notice_device_id']  = deviceId
        noticeDevice['platform']          = Platform.OS === 'android' ? 'ANDROID' : 'IOS####'
        noticeDevice['vendor']            = 'ALI'
        console.log('user.token, user.site_id', user.token, user.site_id)
        noticeDiviceActions.saveNoticeDevice(user.token, user.site_id, noticeDevice);
    })
    .catch((error)=>{
        console.log("getDeviceId() failed", error);
    });

    
    console.log('noticeDiviceActions', noticeDiviceActions, user)
  }

  componentDidMount() {
    this.forceUpdate()
    
    let { params } = this.props.navigation.state; 
    if (!params || !params.article) {
      this.initParams();
    }

    AliyunPush.addListener(this.onMessage);

    AppState.addEventListener("change", (newState) => {
      if (newState === "active") {
        this.forceUpdate();
      }
    });
    
    const { userActions } = this.props;
    InteractionManager.runAfterInteractions(() => {
      store.get('token')
        .then(token => {
          userActions.requestUser(token)
        })
    });
    // DeviceEventEmitter.addListener('aliyunPushReceived', this.onMessage);
  }

  componentWillUnmount() {
    AliyunPush.removeListener(this.onMessage);
    // DeviceEventEmitter.removeListener('aliyunPushReceived', this.onMessage);
  }

  navigateToLink (link ) {
    this.go(link)
  };

  async go (link) {
    try {
      const { navigate } = this.props.navigation;
      const url = await link();
      navigate('scrm', {
        article: {
          url: url,
          title: '',
        }
      });
    } catch(err) {
      console.log(err, 'err')
    }
  }

  onMessage(e){
    console.log("Notification Received.Title:", e);
    let context = this
    try {
        let extras = e.extras
        if (extras.link) {
          let link = JSON.parse(decodeURIComponent(extras.link))
          let linkMethod = () => getLinkSimple(link)
          console.log(link , ' link ')
          if (e.actionIdentifier === 'opened') {
            this.navigateToLink(linkMethod)
          } else {
            Alert.alert(
              '通知',
              e.body,
              [
                {text: '好的', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
                {text: '立即查看', onPress: () => context.navigateToLink(linkMethod)},
              ],
              { cancelable: true }
            )
          }
      }
    } catch (e) {
      console.log(e)
    }
    // alert("Message Received. Title:" + e.title + ", Content:" + e.content);
    // alert("Notification Message Received. Title:" + e.title + ", Content:" + e.body + ", extra: " + JSON.stringify(e));
  }
  onNotification(e){
    // alert("Notification Received.Title:" + e.title + ", Content:" + e.content);
    console.log("Notification Received.Title:" + e.title + ", Content:" + e.content);
  }
  onNotificationOpened(e) {
    // alert("Notification Clicked", e);
    console.log("Notification Clicked", e)
  }
  onNotificationRemoved(e) {
    alert("Notification removed");
  }

  async initParams () {
    let homeLink = await HOME_ROUTE();
    this.setState({
      article: {
        "url": homeLink,
        "title": "工作台",
      }
    })
  }

  render() {
    let props = Object.assign({}, (this.props || {}), this.state);
    return <SCRMWebViewPage {...props} />;
  }
}

const mapStateToProps = (state) => {
  const { auth, team, user } = state;
  return {
    auth,
    team,
    user
  };
};

const mapDispatchToProps = (dispatch) => {
  const authActions = bindActionCreators(authCreators, dispatch);
  const teamActions = bindActionCreators(teamCreators, dispatch); // test code
  const noticeDiviceActions = bindActionCreators(noticeDeviceCreators, dispatch); // test code
  const msgActions = bindActionCreators(msgCreators, dispatch); // test code
  const userActions = bindActionCreators(userCreators, dispatch); // test code

  return {
    authActions,
    teamActions,
    msgActions,
    userActions,
    noticeDiviceActions // test code
  };
};

const styles = StyleSheet.create({
  refreshStyle: {
    padding: 4
  },
  refreshTextStyle: {
    marginRight: 4,
    color: 'white',
    fontSize: 16
  }
});

export default connect(mapStateToProps, mapDispatchToProps)(MainContainer);
